import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class a6 {
    public static List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> list = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            // 跳过第一个元素的重复值
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int left = i + 1, right = nums.length - 1;
            while (left < right) {
                int sum = nums[left] + nums[right] + nums[i];
                if (sum == 0){
                    list.add(new ArrayList<>(Arrays.asList(nums[left], nums[right], nums[i])));
                    // 跳过第二个元素的重复值
                    while (left < right && nums[left] == nums[left + 1]) left++;
                    // 跳过第三个元素的重复值
                    while (left < right && nums[right] == nums[right - 1]) right--;
                    left++;
                    right--;
                } else if (sum < 0) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        return list;
    }

    public static void main(String[] args) {
        int[] nums = {-1, 0, 1, 2, -1, -4};
        System.out.println(threeSum(nums));
    }
}
